//
//  FieldsManager.m
//  Task Views
//
//  Created by Chris Karr on 3/15/09.
//  Copyright 2009 Chris J. Karr. All rights reserved.
//

#import "FieldsManager.h"


@implementation FieldsManager

- (void) awakeFromNib
{
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh:) name:@"refresh_fields" object:nil];
}

- (void) refresh:(NSNotification *) theNote
{
	NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
	
	NSMutableSet * seenKeys = [NSMutableSet setWithObject:@"Hide"];
	
	for (NSDictionary * task in [tasks arrangedObjects])
	{
		for (id key in [task allKeys])
		{
			if (![seenKeys containsObject:key])
			{
				NSDictionary * keyDict = [NSDictionary dictionaryWithObject:key forKey:@"name"];
				
				if (![[fields arrangedObjects] containsObject:keyDict])
					[fields addObject:keyDict];
				
				[seenKeys addObject:key];
			}
		}
	}
	
	NSDictionary * listColumns = [defaults objectForKey:@"list_columns"];
	
	if (listColumns == nil)
		listColumns = [NSDictionary dictionary];
	
	NSMutableDictionary * newColumns = [NSMutableDictionary dictionaryWithDictionary:listColumns];
	
	for (NSString * name in [seenKeys allObjects])
	{
		if ([newColumns valueForKey:name] == nil)
			[newColumns setValue:[NSNumber numberWithBool:NO] forKey:name];
	}
	
	[defaults setObject:newColumns forKey:@"list_columns"];
	
	NSSortDescriptor * sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
	
	[fields setSortDescriptors:[NSArray arrayWithObject:sort]];
	
	[sort release];
}

@end
